﻿using System;
using System.Activities;

namespace NMemcached.Client.Activities
{
    /// <summary>
    /// Increments or decrements a cached value
    /// </summary>
    public sealed class IncrementDecrementActivity : KeyedMemecachedActivity
    {
        /// <summary>
        /// Gets or sets a value indicating if the increment or decrement command is sent
        /// </summary>
        public InArgument<bool> IsIncrement { get; set; }

        /// <summary>
        /// Gets or sets the value by which the cache item is incremented or decremented
        /// </summary>
        public InArgument<ulong> Count { get; set; }

        /// <summary>
        /// Gets or sets the cache value after the increment or decrement operation
        /// </summary>
        public OutArgument<ulong> Result { get; set; }

        /// <summary>
        /// Initializes a new instance of the IncrementDecrementActivity class
        /// </summary>
        public IncrementDecrementActivity()
            : base()
        {
            this.IsIncrement = true;
            this.Count = 1;
        }

        /// <summary>
        /// Performs the execution of the activity
        /// </summary>
        /// <param name="context">The execution context under which the activity executes</param>
        protected override void Execute(CodeActivityContext context)
        {
            base.Execute(context);

            bool increment = this.IsIncrement.Get(context);
            ulong count = this.Count.Get(context);

            if (String.IsNullOrWhiteSpace(this.CacheKey))
            {
                throw new ArgumentNullException("Key");
            }
            else
            {
                ulong result = 0;
                if (increment)
                {
                    result = this.CacheConnection.Increment(this.CacheKey, count);
                }
                else
                {
                    result = this.CacheConnection.Decrement(this.CacheKey, count);
                }

                this.Result.Set(context, result);
            }
        }
    }
}
